package com.woniuxy.thred.lock;

/**
 * description: DeadLock <br>
 * date: 2022/2/6 1:55 下午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * 死锁：过多的同步可能造成互相不释放资源
 * 从而相互等待，一般发生于同步中持有多个对象的锁
 */
public class DeadLock {
    public static void main(String[] args) {
        Markup m1 = new Markup(0, "zs");
        Markup m2 = new Markup(1, "ls");
        m1.start();
        m2.start();
    }
}


//口红
class Lipstick {

}

//镜子
class Mirror {

}

//化妆
class Markup extends Thread {
    //一个镜子
    static Lipstick lipstick = new Lipstick();
    //一个口红
    static Mirror mirror = new Mirror();
    //选择
    int choice;
    //名字
    String girl;

    public Markup(int choice, String girl) {
        this.choice = choice;
        this.girl = girl;
    }

    @Override
    public void run() {
        //化妆
        markup();
    }

    //互相持有对方的对象锁--->可能1造成死锁
    private void markup() {
        if (choice == 0) {
            //获得口红的锁
            synchronized (lipstick) {
                System.out.println(this.girl + "涂口红");
                //1秒后想拥有镜子
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //锁套锁会出现死锁
//                //获得镜子的锁
//                synchronized (mirror){
//                    System.out.println(this.girl+"照镜子");
//                }
            }
            //获得镜子的锁
            synchronized (mirror) {
                System.out.println(this.girl + "照镜子");
            }
        } else {
            synchronized (mirror) {
                System.out.println(this.girl + "照镜子");
                //2秒后想拥有口红的锁
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
//                //获得镜子的锁（锁套锁会出现死锁）
//                synchronized (lipstick){
//                    System.out.println(this.girl+"涂口红");
//                }
                //获得镜子的锁
                synchronized (lipstick) {
                    System.out.println(this.girl + "涂口红");
                }
            }
        }
    }
}